/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.yuhanginfo.modules.sys.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.yuhanginfo.common.config.Global;
import com.yuhanginfo.common.persistence.Page;
import com.yuhanginfo.common.web.BaseController;
import com.yuhanginfo.common.utils.StringUtils;
import com.yuhanginfo.modules.sys.entity.Area;
import com.yuhanginfo.modules.sys.entity.Goods;
import com.yuhanginfo.modules.sys.entity.GoodsCombStore;
import com.yuhanginfo.modules.sys.entity.Orders;
import com.yuhanginfo.modules.sys.entity.Store;
import com.yuhanginfo.modules.sys.entity.User;
import com.yuhanginfo.modules.sys.entity.YongUser;
import com.yuhanginfo.modules.sys.service.AreaService;
import com.yuhanginfo.modules.sys.service.GoodsComboService;
import com.yuhanginfo.modules.sys.service.GoodsService;
import com.yuhanginfo.modules.sys.service.OrdersService;
import com.yuhanginfo.modules.sys.service.StoreService;
import com.yuhanginfo.modules.sys.service.YongUserService;
import com.yuhanginfo.modules.sys.utils.UserUtils;

/**
 * 门店管理Controller
 * @author yangs
 * @version 2017-09-11
 */
@Controller
@RequestMapping(value = "${adminPath}/sys/store")
public class StoreController extends BaseController {

	@Autowired
	private StoreService storeService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private GoodsService goodsService ;
	@Autowired
    private YongUserService yongUserService;
	@Autowired
	private OrdersService ordersService;
	@Autowired
	private GoodsComboService goodsComboService;
	
	private static final String REDIRECT = "redirect:"+Global.getAdminPath()+"/sys/store/?repage";
	
	@ModelAttribute
	public Store get(@RequestParam(required=false) String id) {
		Store entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = storeService.get(id);
		}
		if (entity == null){
			entity = new Store();
		}
		return entity;
	}
	
	@RequiresPermissions("sys:store:view")
	@RequestMapping(value = {"list", ""})
	public String list(Store store, HttpServletRequest request, HttpServletResponse response, Model model) {
		store.setSysUserId(UserUtils.getUser().getId());
		Page<Store> page = storeService.findPage(new Page<Store>(request, response), store); 
		List<Area> area=areaService.areaStoreList();
		model.addAttribute("area", area);
		model.addAttribute("page", page);
		return "modules/sys/storeMessage/storeList";
	}

	
	@RequiresPermissions("sys:store:view")
	@RequestMapping(value = "form")
	public String form(Store store, Model model,String pa) {
		if(store.getCnName()==null){
			model.addAttribute("area", areaService.useStoreList());
		}else{
			model.addAttribute("area", areaService.areaStoreList());
		}
		model.addAttribute("pa", pa);
		model.addAttribute("store", store);
		if("2".equals(pa)){
			return "modules/sys/storeMessage/storeView";
		}else{
			return "modules/sys/storeMessage/storeForm";
		}
		
	}

	@RequiresPermissions("sys:store:edit")
	@RequestMapping(value = "save")
	public String save(Store store, Model model, RedirectAttributes redirectAttributes,String pa) {
		store.setCreateDate(new Date());
		List<Store> list=storeService.selectTypeList(store.getType());
	    if(!"1".equals(pa)){
		if("1".equals(store.getType())){
			Integer code=10001+list.size();
			store.setCode(code.toString());
		}else if("2".equals(store.getType())){
			Integer code=20001+list.size();
			store.setCode(code.toString());
		}
	    }
		if (!beanValidator(model, store)) {
			return form(store, model, pa);
		}
		User us = UserUtils.getUser();
		store.setCreateBy(us);
		store.setDelFlag("0");
		store.setStatus("1");
		store.setUpdateDate(new Date());
		storeService.save(store);
		addMessage(redirectAttributes, "保存门店管理成功");
		return REDIRECT;
	}
	
	@RequiresPermissions("sys:store:edit")
	@RequestMapping(value = "delete")
	public String delete(Store store, RedirectAttributes redirectAttributes ,String id) {
		//查询所属自己门店的商品
		List<Goods> goods1=goodsService.selectByStoreCode(store.getCode());
		//查询所属门店但不是该门店的上架商品
		List<Goods> goods2=goodsService.selectByStoreCodes(store.getCode());
		//查询该门店绑定的会员
		List<YongUser> userList1=yongUserService.selectByStoreCode(store.getCode());
		//查询该门店下绑定的业务员
		List<YongUser> userList2=yongUserService.selectByStoreCodes(store.getCode());
		//查看该门店下是否有订单
		List<Orders> storeOrderList=ordersService.selectByStoreCode(store.getCode());
		//查看该门店下是否有套餐
		List<GoodsCombStore> goodsCombStoreList=goodsComboService.selectByStoreCode(store.getCode());
		store.setId(id);
		store.setDelFlag("1");
		boolean b=true;
		if(!goods1.isEmpty()){
			addMessage(redirectAttributes, "该门店下有自己的商品，删除失败!");
            b=false;
		}
		if(b){
			if(!goods2.isEmpty()){
				addMessage(redirectAttributes, "该门店存在自营上架的商品，删除失败!");
			}else if(!userList1.isEmpty()){
				addMessage(redirectAttributes, "该门店存在绑定的会员，删除失败!");
			}else if(!userList2.isEmpty()){
				addMessage(redirectAttributes, "该门店存在所属的业务员，删除失败!");
			}else if(!storeOrderList.isEmpty()){
				addMessage(redirectAttributes, "该门店存在订单，删除失败!");
			}else if(!goodsCombStoreList.isEmpty()){
				addMessage(redirectAttributes, "该门店存在套餐，删除失败!");
			}
			storeService.delete(store);
			addMessage(redirectAttributes, "删除门店成功");
		}
		return REDIRECT;
	}
	
	@ResponseBody
	@RequiresPermissions("sys:store:view")
	@RequestMapping(value = "couldDelete")
	public Map<String,Object> couldDelete(Store store) {
		Map<String,Object> map=new HashMap<>();
		//查询所属自己门店的商品
		List<Goods> goods1=goodsService.selectByStoreCode(store.getCode());
		map.put("goods1", goods1);
		//查询所属门店但不是该门店的上架商品
		List<Goods> goods2=goodsService.selectByStoreCodes(store.getCode());
		map.put("goods2", goods2);
		//查询该门店绑定的会员
		List<YongUser> userList1=yongUserService.selectByStoreCode(store.getCode());
		map.put("userList1", userList1);
		//查询该门店下绑定的业务员
		List<YongUser> userList2=yongUserService.selectByStoreCodes(store.getCode());
		map.put("userList2", userList2);
		return map;
	}
   
	@RequiresPermissions("sys:store:edit")
	@RequestMapping(value = "upStore")
	public String upStore( RedirectAttributes redirectAttributes,String id,String status) {
		Store store=new Store();
		store.setUpdateDate(new Date());
		User us = UserUtils.getUser();
		store.setUpdateBy(us);
		store.setStatus(status);
		store.setId(id);
		storeService.upStore(store);
		addMessage(redirectAttributes, "门店状态修改成功!");
		return REDIRECT;
	}
	
	//门店区域管理
	@RequiresPermissions("sys:store:view")
	@RequestMapping(value = "storeAreaList")
	public String storeAreaList(RedirectAttributes redirectAttributes,Area area, HttpServletRequest request,HttpServletResponse response, Model model){
		Page<Area> page=areaService.storeAreaList(new Page<Area>(request, response), area);
		model.addAttribute("page", page);
		return "modules/sys/storeMessage/areaList";	
	}
	
	//区域删除
	@RequiresPermissions("sys:store:edit")
	@RequestMapping(value = "areaDelete")
	public String areaDelete(Area area, RedirectAttributes redirectAttributes ) {
		List<Store> st=storeService.sectByClassify(area.getId());
	    if(!st.isEmpty()){
	    	addMessage(redirectAttributes, "该区域下有门店删除失败!");
	    }else{
	    	areaService.delete(area);
	    	addMessage(redirectAttributes, "删除成功!");
	    }
		return "redirect:"+Global.getAdminPath()+"/sys/store/storeAreaList?repage";
	}
	
	//区域显示
	@RequiresPermissions("sys:store:view")
	@RequestMapping(value = "areaForm")
	public String areaForm(Area area, Model model) {
		model.addAttribute("area", area);
		return "modules/sys/storeMessage/areaForm";
	}
	
	//区域保存
	@RequiresPermissions("sys:store:edit")
	@RequestMapping(value = "areaSave")
	public String areaSave(Area area, Model model, RedirectAttributes redirectAttributes) {
		User us = UserUtils.getUser();
		area.setType("5");
		area.setDelFlag("0");
		area.setParentIds("0");
		area.setSort(0);
		area.setCreateDate(new Date());
		area.setCreateBy(us);
		if (!beanValidator(model, area)){
			return areaForm(area, model);
		}
		areaService.save(area);;
		addMessage(redirectAttributes, "保存门店区域管理成功");
		return "redirect:"+Global.getAdminPath()+"/sys/store/storeAreaList?repage";
	}
	
	  //区域显示
		@RequiresPermissions("sys:store:view")
		@RequestMapping(value = "editAreaForm")
		public String editAreaForm(String id, Model model) {
			Area area=areaService.get(id);
			model.addAttribute("area", area);
			return "modules/sys/storeMessage/areaForm";
		}
		
		/**
		 * 角色选择标签（roleselect.tag）
		 */
		@RequestMapping(value = "storeselect")
		public String roleselect(HttpServletRequest request, Model model) {
			List<Store> allStore = new ArrayList<>();
			Store s1 = new Store();
			s1.setId("1");
			s1.setCnName("a");
			allStore.add(s1);
		
			List<Store> storeList = new ArrayList<>();
			Store s2 = new Store();
			s1.setId("2");
			s1.setCnName("b");
			storeList.add(s2);
			model.addAttribute("allStore", allStore);
			model.addAttribute("storeList", storeList);
			model.addAttribute("store", new Store());
			model.addAttribute("storeId", "1");
			return "modules/sys/tagStoreselect";
		}
		
		@ResponseBody
		@RequiresPermissions("sys:store:view")
		@RequestMapping(value = "storeType")
		public Map<String,Object> storeType(String id){
			Map<String,Object> map=new HashMap<>();
			Store store=storeService.get(id);
			if(store!=null){
				map.put("type", store.getType());
			}
			return map;
		}
		
		@ResponseBody
		@RequiresPermissions("sys:store:view")
		@RequestMapping(value = "yzAreaName")
		public Map<String,Object> yzAreaName(String name,String id) {
			List<Area> list=areaService.selectcnName(name);
			Map<String,Object> map=new HashMap<>();
			if(id!=""&&id!=null){
				if(list.size()>1 && list.get(0).getId().equals(id)){
					map.put("st", 1);
				}
				if(!list.isEmpty() && !list.get(0).getId().equals(id)){
					map.put("st", 1);
				}
			}else{
				if(!list.isEmpty()){
					map.put("st", 1);
				}
			}
			return map;
		}
		
}